package liuliu.throughwaring.control.task;

import android.content.Context;
import android.location.Location;
import android.util.Log;

import net.tsz.afinal.FinalDb;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import liuliu.custom.method.Utils;
import liuliu.throughwaring.control.add.police.person.IRegPersonView;
import liuliu.throughwaring.control.add.police.police.IRegPoliceView;
import liuliu.throughwaring.control.add.police.company.IRegUnitView;
import liuliu.throughwaring.control.add.police.work.IRegTransationView;
import liuliu.throughwaring.control.login.ILoginView;
import liuliu.throughwaring.control.net.HttpTask;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.InvokeReturn;
import liuliu.throughwaring.model.PersonModel;
import liuliu.throughwaring.model.PoliceModel;
import liuliu.throughwaring.model.TerminalModel;
import liuliu.throughwaring.model.TransactionModel;

/**
 * Created by Administrator on 2015/11/14.
 */
public class addTask {
    Context mContext;
    FinalDb db;
    HttpTask task;
    Utils mUtil;

    public addTask(Context context) {
        mContext = context;
        db = FinalDb.create(context);
        task = new HttpTask(mContext);
        mUtil = new Utils(context);
    }

    //更新设备所在位置
    public void UpdateLocation(String eastPoint, String northPoint) {
        task = new HttpTask(mContext);
        task.start("UpdateTerminalLocation", "TerminalEastPoint=" + eastPoint + "&TerminalNorthPoint=" + northPoint, "", new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    System.out.println("location 更新成功");
                } else {
                    System.out.println("location 更新失败");
                }
            }
        });
    }

    //添加民警信息
    public void addPolice(final PoliceModel policeModel, final IRegPoliceView iRegPoliceView) {
        List<TerminalModel> list = db.findAll(TerminalModel.class);
        if (list.size() > 0) {
            policeModel.setPoliceArea(list.get(0).getTerminalArea());
        }
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        policeModel.setPoliceCreateTime(str);
        policeModel.setPoliceWorkingStatus("OnJob");
        final PoliceModel pm = policeModel;
        task.start("AddPolice", policeModel.getInfo(), null, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                boolean isSuccess = false;
                if (result) {
                    if (invokeReturn != null) {
                        List<PoliceModel> lists = db.findAllByWhere(PoliceModel.class, "PoliceId='"+policeModel.getPoliceId()+"'");
                        if (lists != null) {
                            if (lists.size() > 0) {
                                pm.setIsUpLoad("1");
                                pm.setId(lists.get(0).getId());
                                db.update(pm);

                            } else {
                                pm.setIsUpLoad("1");
                                db.save(pm);
                            }
                        }
                        isSuccess = true;
                    }
                }
                if (iRegPoliceView != null) {
                    if (isSuccess) {
                        iRegPoliceView.onRegResult(true, "添加成功");
                    } else {
                        pm.setIsUpLoad("0");
                        db.save(pm);
                        iRegPoliceView.onRegResult(true, "本地添加成功");
                    }
                }
            }
        });
    }

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 添加企业信息
     */

    public void addCompany(final CompanyModel companyModel, final IRegUnitView iRegUnitView) {
        companyModel.setCompanyPoliceId(Utils.ReadString("PoliceId"));
        List<TerminalModel> list = db.findAll(TerminalModel.class);
        if (list.size() > 0) {
            companyModel.setCompanyArea(list.get(0).getTerminalArea());
        }
        companyModel.setCompanyEastPoint(Utils.ReadString("Longitud"));
        companyModel.setCompanyNorthPoint(Utils.ReadString("Latitude"));
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        if (null == companyModel.getCompanyCreateTime() || companyModel.getCompanyCreateTime().equals("")) {
            companyModel.setCompanyCreateTime(str);
        }
        companyModel.setCompanyChangeTime(str);
        if (Utils.isNetworkAvailable(mContext)) {//网络正常
            task.start("AddCompany", companyModel.getAddInfo(), "", new HttpTask.TaskListener() {
                        @Override
                        public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                            if (result) {
                                if (invokeReturn != null) {
                                    Log.i("oooo", "invokeReturn.getMessage()):" + invokeReturn.getMessage());
                                    if (invokeReturn.isSuccess()) {
                                        CompanyModel c = companyModel;
                                        List<CompanyModel> list = db.findAllByWhere(CompanyModel.class, "CompanyId='" + companyModel.getCompanyId() + "'");
                                        if (list.size() > 0) {
                                            c.setId(list.get(0).getId());
                                            db.update(c);
                                        } else {
                                            c.setIsUpLoad("1");
                                            c.setCompanyId(invokeReturn.getMessage());
                                            db.save(c);
                                        }
                                    }
                                }
                            }else{
                                CompanyModel c = companyModel;
                                List<CompanyModel> list = db.findAllByWhere(CompanyModel.class, "CompanyId='" + companyModel.getCompanyId() + "'");
                                if (list.size() > 0) {
                                    c.setId(list.get(0).getId());
                                    db.update(c);
                                } else {
                                    c.setIsUpLoad("1");
                                    c.setCompanyId(invokeReturn.getMessage());
                                    db.save(c);
                                }
                        }
                            if (iRegUnitView != null) {
                                if (result) {
                                    iRegUnitView.onRegUnitResult(true, "");
                                } else {
                                    iRegUnitView.onRegUnitResult(false, "");
                                }
                            }
                        }
                    }
            );
        } else {
            companyModel.setIsUpLoad("0");
            db.save(companyModel);
            iRegUnitView.onRegUnitResult(true, "添加成功");
        }
    }

    /**
     * 添加人员信息
     */

    public void addPerson(final PersonModel person, final IRegPersonView iRegPersonView) {
        task = new HttpTask(mContext);
        TerminalModel terminalModel = db.findAll(TerminalModel.class).get(0);
        person.setPersonTerminalId(terminalModel.getTerminalId());
        Location location = mUtil.getLocation();
        person.setPersonEastPoint(location.getLongitude() + "");
        person.setPersonNorthPoint(location.getLatitude() + "");
        PersonModel newPerson = new PersonModel();
        newPerson.setPersonCompanyId(person.getPersonCompanyId());
        newPerson = getNextPersonId(newPerson);
        if (person.getPersonId().equals("")) {
            person.setPersonId(newPerson.getPersonId());
            person.setPersonIndex(newPerson.getPersonIndex());
            person.setPersonDate(newPerson.getPersonDate());
        }
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        person.setPersonCreateTime(str);
        person.setCheckOutTime(str);
        final PersonModel personModel = person;
        if (Utils.isNetworkAvailable(mContext)) {//网络正常
            task.start("AddPerson", person.getInfo(), "", new HttpTask.TaskListener() {
                        @Override
                        public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                            boolean isSuccess = false;
                            if (result) {
                                if (invokeReturn != null) {
                                    if (invokeReturn.isSuccess()) {
                                        personModel.setIsUpLoad(true);
                                        isSuccess = true;
                                        List<PersonModel> list = db.findAllByWhere(PersonModel.class, "PersonId='" + personModel.getPersonId() + "'");
                                        if (list.size() > 0) {
                                            personModel.setId(list.get(0).getId());
                                            db.update(personModel);
                                        } else {
                                            db.save(personModel);
                                        }
                                    }
                                }
                            }
                            if (iRegPersonView != null) {
                                if (isSuccess) {
                                    iRegPersonView.onRegPersonResult(true, person.getPersonId());
                                } else {
                                    iRegPersonView.onRegPersonResult(false, "提交失败！");
                                }
                            }
                        }
                    }
            );
        } else if (db != null) {//网络异常(保存到本地)
            personModel.setIsUpLoad(false);
            db.save(personModel);
            iRegPersonView.onRegPersonResult(true, personModel.getPersonId());
        }
    }

    private PersonModel getNextPersonId(PersonModel p) {
        p.setPersonDate(Utils.getTodayString());
        List<PersonModel> list = db.findAllByWhere(PersonModel.class, "PersonId like '%" + p.getPersonDate() + "%' order by PersonId desc");
        int index = 0;
        if (list.size() > 0) {
            String id = list.get(0).getPersonId();
            index = Integer.parseInt(id.substring(id.length() - 4, id.length())) + 1;
        }
        p.setPersonId(String.format("%s%s%04d", p.getPersonCompanyId(), p.getPersonDate(),
                index));
        return p;
    }

    /**
     * 添加事务
     */
    public void addTransaction(final TransactionModel transactionModel, final IRegTransationView iview) {
        task = new HttpTask(mContext);
        TransactionModel transaction;
        transaction = getNewTransactionId(transactionModel);
        transactionModel.setTransactionId(transaction.getTransactionId());
        transactionModel.setTransactionIndex(transaction.getTransactionIndex());
        transactionModel.setTransactionDate(transaction.getTransactionDate());
        Location location = mUtil.getLocation();
        transactionModel.setTransactionEastPoint(location.getLongitude() + "");
        transactionModel.setTransactionNorthPoint(location.getLatitude() + "");
        transactionModel.setTransactionTerminalId(Utils.getImei(mContext));
        if (Utils.isNetworkAvailable(mContext)) {//网络正常
            task.start("AddTransaction", transactionModel.getInfo(), "", new HttpTask.TaskListener() {
                @Override
                public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                    if (result) {
                        if (invokeReturn != null) {
                            if (invokeReturn.isSuccess()) {
                                transactionModel.setIsUpLoad(true);
                                db.save(transactionModel);
                                iview.onRegTransactionResult(true, "添加事务成功", transactionModel.getTransactionId());
                            }
                        }
                    }
                }
            });
        } else if (db != null) {//网络异常
            transactionModel.setIsUpLoad(false);
            db.save(transactionModel);
            iview.onRegTransactionResult(true, "添加事务成功", transactionModel.getTransactionId());
        }
    }

    private TransactionModel getNewTransactionId(TransactionModel t) {
        TransactionModel transaction = new TransactionModel();
        transaction.setTransactionDate(Utils.getTodayString());
        List<TransactionModel> list = db.findAllByWhere(TransactionModel.class, "TransactionDate='" + t.getTransactionDate() + "' order by TransactionIndex");
        int index = 0;
        if (list.size() > 0) {
            index = list.get(0).getTransactionIndex();
        }
        index++;
        transaction.setTransactionIndex(index);
        transaction.setTransactionId(String.format("%s%s%04d", Utils.getImei(mContext),
                transaction.getTransactionDate(), transaction.getTransactionIndex()));
        return transaction;
    }

    //设备绑定民警信息
    public void UpdateTerminalPolice(final ILoginView iLoginView) {
        final String pid = Utils.ReadString("PoliceId");
        task = new HttpTask(mContext);
        task.start("UpdateTerminalPolice", "PoliceId=" + pid, "", new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (iLoginView != null) {
                        List<TerminalModel> list = db.findAll(TerminalModel.class, "TerminalId='" + Utils.getImei(mContext) + "'");
                        if (list.size() > 0) {
                            TerminalModel t = list.get(0);
                            t.setPoliceId(pid);
                            db.update(t);
                        }
                        iLoginView.UpdatePolice(true, "登录成功");
                        //System.out.println("绑定民警成功..pid;;;;;"+pid);
                    } else {
                        iLoginView.UpdatePolice(false, "登录失败");
                        //System.out.println("绑定民警失败");
                    }
                } else {
                    iLoginView.UpdatePolice(false, "登录失败");
                    //System.out.println("绑定民警失败");
                }
            }
        });
    }
}
